package com.yanchangapp.ui.activity.base;

import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.zxl.baselib.baseapp.AppManager;
import com.zxl.baselib.bean.response.BaseResponse;
import com.zxl.baselib.ui.base.BaseActivity;
import com.zxl.baselib.ui.base.BaseObserver;
import com.zxl.baselib.ui.base.BasePresenter;
import com.zxl.baselib.ui.base.ExceptionHandle;
import com.zxl.baselib.util.CheckUtils;
import com.yanchangapp.R;
import com.yanchangapp.base.ApiRetrofit;
import com.yanchangapp.base.HeadApiRetrofit;
import com.yanchangapp.commom.AppConstant;
import com.yanchangapp.model.cache.UserCache;
import com.yanchangapp.ui.activity.BaseTimeTask;
import com.yanchangapp.ui.activity.BaseTimeTaskListener;
import com.zxl.baselib.util.NetUtils;
import com.zxl.baselib.util.ui.UIUtils;

import java.util.Timer;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * 修改手机号页面
 */
public class ChangePhoneActivity extends BaseActivity implements BaseTimeTaskListener {

    @BindView(R.id.ivToolbarNavigation)
    ImageView ivToolbarNavigation;
    @BindView(R.id.vToolbarDivision)
    View vToolbarDivision;
    @BindView(R.id.tvToolbarTitle)
    TextView tvToolbarTitle;
    @BindView(R.id.etNewPhone)
    AppCompatEditText etNewPhone;
    @BindView(R.id.etSmsCode)
    AppCompatEditText etSmsCode;
    @BindView(R.id.btnSendSms)
    Button btnSendSms;
    @BindView(R.id.btnSubmit)
    Button btnSubmit;
    @BindView(R.id.tvPhone)
    TextView tvPhone;

    private Timer mTimer;
    private int mCount;
    private String mMobile;

    @Override
    protected void init() {

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_change_phone;
    }

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected void initView(Bundle savedInstanceState) {
        tvToolbarTitle.setText("修改手机号");
        tvPhone.setText(UserCache.getMobile());
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void initListener() {

    }

    @OnClick({R.id.ivToolbarNavigation, R.id.btnSendSms, R.id.btnSubmit})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ivToolbarNavigation:
                finish();
                break;
            case R.id.btnSendSms:
                actionSendSms();
                break;
            case R.id.btnSubmit:
                doSubmit();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (mTimer != null){
            mTimer.cancel();
            mTimer = null;
        }
        super.onDestroy();

    }

    private void initTimer(){
        mCount = 60;
        // 设置发送按钮不可点击
        btnSendSms.setEnabled(false);
        if (mTimer == null){
            mTimer = new Timer();
        }
        mTimer.schedule(new BaseTimeTask(this),0,1000);
    }

    @Override
    public void doTimeTask() {
        runOnUiThread(() -> {
            if (mCount > 0){
                btnSendSms.setText(String.valueOf(mCount));
                mCount --;
            }else {
                mTimer.cancel();
                btnSendSms.setText("获取验证码");
                // 设置发送按钮可以点击...
                btnSendSms.setEnabled(true);
                mTimer = null;
            }
        });
    }

    public void reBackTimeTask(){
        mTimer.cancel();
        mTimer = null;
        btnSendSms.setText("获取验证码");
        // 设置发送按钮可以点击...
        btnSendSms.setEnabled(true);
    }

    // 发送验证码
    public void actionSendSms(){
        mMobile = etNewPhone.getText().toString();
        if (TextUtils.isEmpty(mMobile)){
            UIUtils.showToast("请输入新的手机号码");
            return;
        }

        if (!CheckUtils.isMobile(mMobile)){
            UIUtils.showToast("请输入正确的手机号码");
            return;
        }
        if (!NetUtils.isConnectedAndToast(this)){
            return;
        }
        netQuerySms();
        initTimer();
    }

    public void netQuerySms(){
        ApiRetrofit.getInstance().getSms(mMobile)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponse>() {
                    @Override
                    public void onNext(BaseResponse baseResponse) {
                        if (baseResponse.getCode() == AppConstant.REQUEST_SUCCESS ||
                         baseResponse.getCode() == 203){
                            UIUtils.showToast("短信发送成功");
                        }else {
                            reBackTimeTask();
                            UIUtils.showToast(baseResponse.getMsg());
                        }
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {
                        UIUtils.showToast("短信发送失败");
                        reBackTimeTask();
                    }
                });
    }

    // 修改密码-提交点击事件
    public void doSubmit(){
        mMobile = etNewPhone.getText().toString();
        if (TextUtils.isEmpty(mMobile)){
            UIUtils.showToast("请输入新的手机号码");
            return;
        }

        if (!CheckUtils.isMobile(mMobile)){
            UIUtils.showToast("请输入正确的手机号码");
            return;
        }

        String smsCode = etSmsCode.getText().toString();
        if (TextUtils.isEmpty(smsCode)){
            UIUtils.showToast("请输入验证码");
            return;
        }

        if (!NetUtils.isConnectedAndToast(this)){
            return;
        }

        doChangePhone(smsCode);
    }

    // 修改手机号具体的业务
    private void doChangePhone(String sms) {
        HeadApiRetrofit.getInstance().updateMobile(UserCache.getID(),mMobile,sms)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new BaseObserver<BaseResponse>() {
                @Override
                public void onNext(BaseResponse baseResponse) {
                    if (baseResponse.getCode() == AppConstant.REQUEST_SUCCESS){
                        UIUtils.showToast("修改手机号成功");
                        doLogout();
                    } else {
                        UIUtils.showToast(baseResponse.getMsg());
                    }
                }

                @Override
                public void onError(ExceptionHandle.ResponseException exception) {
                    UIUtils.showToast("修改手机号失败");
                }
            });
    }

    // 注销登录
    public void doLogout(){
        Observable.create((ObservableOnSubscribe<Boolean>) emitter -> {
            UserCache.clear();
            emitter.onNext(true);
            emitter.onComplete();
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<Boolean>() {
                    @Override
                    public void onNext(Boolean aBoolean) {
                        AppManager.getAppManager().finishAllActivity();
                        jumpToActivityAndClearTask(LoginActivity.class);
                    }

                    @Override
                    public void onError(ExceptionHandle.ResponseException exception) {

                    }
                });
    }
}
